#!/bin/bash
# shellcheck source=meta-facebook/meta-bletchley/recipes-bletchley/plat-tools/files/bletchley-common-functions
source /usr/libexec/bletchley-common-functions

SWITCH_MDIO_BUS="1e650000.mdio-1"

INNER_PORT_DEV_ID="4"
OUTER_PORT_DEV_ID="3"
RETIMER_MDIO_BUS="1e650018.mdio-1"

get_switch_port_link_st()
{
    local port_phy_id=$1

    if PORT_ST_VAL="$(mdio "$SWITCH_MDIO_BUS" phy "$port_phy_id" 0x00)"; then
        PORT_ST_VAL="${PORT_ST_VAL:2}"
        if [ "$((16#$PORT_ST_VAL & 16#0800))" -eq "0" ]; then
            PORT_ST="down"
        else
            PORT_ST="up"
        fi
    else
        PORT_ST="mdio failed"
    fi
    echo "${PORT_ST}"
}

get_retimer_port_link_st()
{
    local port_dev_id=$1

    if PORT_ST_VAL="$(mdio "$RETIMER_MDIO_BUS" mmd 0:"$port_dev_id" 0x9002)"; then
        PORT_ST_VAL="${PORT_ST_VAL:2}"
        if [ "$((16#$PORT_ST_VAL & 16#0004))" -eq "0" ]; then
            PORT_ST="down"
        else
            PORT_ST="up"
        fi
    else
        PORT_ST="mdio failed"
    fi
    echo "${PORT_ST}"
}

get_port_link_st()
{
    printf "========================================\n"
    printf "Link Status\n"
    printf "========================================\n"
    printf "Switch:\n"
    for port_phy in $(seq 0 $"$MAX_SLED_NUM")
    do
        printf "  Port %d (%s): %s\n" "${PORT_NUM_MAP[port_phy]}" "${PORT_NAME_MAP[port_phy]}" "$(get_switch_port_link_st "${PORT_NUM_MAP[port_phy]}")"
    done
    printf "\n"
    printf "Retimer:\n"
    printf "  Inner Port (XFI): %s\n" "$(get_retimer_port_link_st "${INNER_PORT_DEV_ID}")"
    printf "  Outer Port (SFI): %s\n" "$(get_retimer_port_link_st "${OUTER_PORT_DEV_ID}")"
    printf "========================================\n\n"
}

get_switch_port_reg_dump()
{
    for port_phy in $(seq 0 $"$MAX_SLED_NUM")
    do
        printf "========================================\n"
        printf "Port %d (%s)\n" "${PORT_NUM_MAP[port_phy]}" "${PORT_NAME_MAP[port_phy]}"
        printf "****************************************\n"
        for reg_offset in {0..31}
        do
            printf "[%02X]: %04X\n" "$reg_offset" "$(mdio "$SWITCH_MDIO_BUS" phy "${PORT_NUM_MAP[port_phy]}" "$reg_offset")"
        done
        printf "========================================\n\n"
    done
}

print_help()
{
    echo "Usage:"
    echo "  $0 <COMMAND>"
    echo ""
    echo "COMMAND:"
    echo "    --link-st"
    echo "        show link status"
    echo ""
    echo "    --port-reg-dump"
    echo "        port registers dump"
    echo ""
}

ACTION_CMD="$1"

if [[ ${ACTION_CMD} =~ -h|--help ]]; then
    print_help
elif [ "${ACTION_CMD}" = "--link-st" ]; then
    get_port_link_st
elif [ "${ACTION_CMD}" = "--port-reg-dump" ]; then
    get_switch_port_reg_dump
else
    echo "Unknow command: $ACTION_CMD"
    print_help
fi
